package com.meisupic.copyright.service.impl;

import com.meisupic.copyright.domain.po.Message;
import com.meisupic.copyright.domain.vo.MessageVo;
import com.meisupic.copyright.repo.MessageRepo;
import com.meisupic.copyright.service.IMessageService;
import com.meisupic.copyright.util.BeanMapper;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

/**
 * @Author lanjian
 * @Date 2018/4/7 下午4:54
 */
@Service
public class MessageServiceImpl implements IMessageService {

  @Autowired
  MessageRepo messageRepo;

  @Override
  public void addMessage(String title, String content, Long userId, Long worksId) {
    Message message = new Message();
    message.setWorksId(worksId);
    message.setContent(content);
    message.setTitle(title);
    message.setReaded(false);
    message.setReceiverId(userId);
    messageRepo.save(message);
  }

  @Override
  public void updateMessage(Long id) {
    Message message = messageRepo.findOne(id);
    message.setReaded(true);
    messageRepo.save(message);
  }

  @Override
  public Page<MessageVo> getPageMessageRecord(Long userId, Pageable pageable) {
    Message whereEntity = new Message();
    whereEntity.setReceiverId(userId);
    Page<Message> messages = messageRepo.findAll(Example.of(whereEntity), pageable);
    List<Message> messageList = messages.getContent();
    List<MessageVo> messageVos = BeanMapper.mapList(messageList, MessageVo.class);
    Page<MessageVo> recordVos = new PageImpl<>(messageVos, pageable, messages.getTotalElements());
    return recordVos;
  }

  @Override
  public List<MessageVo> findLastedMessage(Long userId) {
    List<Message> messages = messageRepo.findTop1ByReceiverIdOrderByCreateTimeDesc(userId);
    List<MessageVo> messageVos = BeanMapper.mapList(messages, MessageVo.class);
    return messageVos;
  }


}
